/*
 * Copyright © Yan Zhenjie. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yanzhenjie.andserver.sample.handler;

import android.content.res.AssetManager;

import com.yanzhenjie.andserver.RequestHandler;
import com.yanzhenjie.andserver.RequestMethod;
import com.yanzhenjie.andserver.SimpleRequestHandler;
import com.yanzhenjie.andserver.annotation.RequestMapping;
import com.yanzhenjie.andserver.exception.NotFoundException;
import com.yanzhenjie.andserver.sample.App;
import com.yanzhenjie.andserver.util.AssetsReader;
import com.yanzhenjie.andserver.view.View;

import org.apache.commons.io.IOUtils;
import org.apache.httpcore.HttpEntity;
import org.apache.httpcore.HttpException;
import org.apache.httpcore.HttpRequest;
import org.apache.httpcore.HttpResponse;
import org.apache.httpcore.entity.ContentType;
import org.apache.httpcore.entity.FileEntity;
import org.apache.httpcore.entity.InputStreamEntity;
import org.apache.httpcore.protocol.HttpContext;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.Charset;

import static com.yanzhenjie.andserver.util.FileUtils.getMimeType;

/**
 * <p>Returns a file.</p>
 * Created by Yan Zhenjie on 2016/7/1.
 */
public class AssetsFileHandler extends SimpleRequestHandler {

    private final AssetsReader mAssetsReader;

    public AssetsFileHandler(AssetManager assetManager){
        this.mAssetsReader = new AssetsReader(assetManager);
    }

    @RequestMapping(method = {RequestMethod.GET})
    public View handle(HttpRequest request, HttpResponse response) throws HttpException, IOException {
        String uri = request.getRequestLine().getUri();//It's different
        URL url = new URL(uri);
        String path = url.getPath();
        InputStream source = mAssetsReader.getInputStream("web"+path);
        if (source == null)
            throw new NotFoundException(uri);

        int length = source.available();
        String mimeType = getMimeType(path);

        HttpEntity httpEntity = new InputStreamEntity(source, length, ContentType.create(mimeType, Charset.defaultCharset()));
        return new View(200, httpEntity);
    }
}
